import React from 'react';
import ProCard from '@ant-design/pro-card';
import styles from '@/pages/market/Item/index.less';
import { Button } from 'antd';
import { ModalForm, ProFormSelect, ProFormText } from '@ant-design/pro-form';
import { useModel } from '@@/plugin-model/useModel';

const ApprovalCard: React.FC = () => {
  // 全局变量
  const { initialState } = useModel('@@initialState');
  if (!initialState) {
    return <div />;
  }
  // 页面变量
  const { item, tokenId, owner, loading } = useModel('item');
  const {
    currentAccount,
    provider,
    contracts: { fileStorageContract },
  } = initialState;
  if (!item) {
    return <div />;
  }

  if (currentAccount?.address !== owner) {
    return <div />;
  }

  return (
    <ProCard
      className={styles.itemCard}
      headerBordered
      bordered
      title="操作"
      loading={loading}
    >
      <ModalForm<{
        tokenId: number;
        contractAddress: string;
      }>
        title="交易授权"
        trigger={<Button type="primary">交易授权</Button>}
        onFinish={async (values) => {
          try {
            const signer = await provider.getSigner();
            const overrides = {
              from: await signer.getAddress(),
              gasPrice: await provider.getGasPrice(),
              gasLimit: 500000,
              nonce: await signer.getTransactionCount(),
            };
            // 预执行合约
            console.log(
              await fileStorageContract.callStatic.approve(
                values.contractAddress,
                values.tokenId,
                overrides,
              ),
            );
            // 实际执行合约
            const tx = await fileStorageContract
              .connect(signer)
              .approve(values.contractAddress, values.tokenId, overrides);
            await tx.wait();
            window.location.reload();
          } catch (e) {
            console.error(e);
          }
          return true;
        }}
      >
        <ProFormText
          name="tokenId"
          label="tokenId"
          disabled
          initialValue={tokenId}
          rules={[
            {
              required: true,
            },
          ]}
        />
        <ProFormSelect
          name="contractAddress"
          label="交易合约地址"
          valueEnum={{
            '0xdB7d6AB1f17c6b31909aE466702703dAEf9269Cf':
              '定价交易：0xdB7d6AB1f17c6b31909aE466702703dAEf9269Cf',
            '0xcBa37ECfA8029838FEBD83b6a877F0e7f1f13b3E':
              '拍卖交易:0xcBa37ECfA8029838FEBD83b6a877F0e7f1f13b3E',
            '0x880EC53Af800b5Cd051531672EF4fc4De233bD5d':
              '授权交易:0x880EC53Af800b5Cd051531672EF4fc4De233bD5d',
          }}
          rules={[
            {
              required: true,
            },
          ]}
        />
      </ModalForm>
    </ProCard>
  );
};

export default ApprovalCard;
